<?php
namespace app\admin\controller;

use think\Controller;

class Category extends Controller
{

    private $obj;
    public function _initialize() {
    
        $this->obj = model("Category");
    }

    public function index()
    {
        $parentId = input('get.parent_id',0,'intval');
        $categorylist = model("Category")->getFirstCategory($parentId);

        return $this->fetch('',[
            'categorylist'=> $categorylist
        ]);


    }

    public function add() {

              $categorys = model("Category")->getNormalFirstCategory();
            
        return $this->fetch('',[
            'categorys'=>$categorys
            ]);
    }
    /**
     * 编辑页面
     */

    public function edit($id=0) {
        if(intval($id) < 1) {
            $this->error("参数不合法");
        }
        $category = model("Category")->get($id);

        $categorys = model("Category")->getNormalFirstCategory();
            
        return $this->fetch('',[
            'categorys'=>$categorys,
            'category'=>$category
            ]);

         
    }


    public function save() {
        //    print_r($_POST);
        // print_r(input('post.'));
        // print_r(request()->post());
            $data = input('post.');
             if (!request()->isPost()){
                 $this->error('请求失败');
             }

            // print_r($data);
            // $validate = validate('Category');
            // if (!$validate->check($data)) {
            //     $this->error($validate->getError());
            // }
           $validate = validate('Category');
        //    if(!$validate->scene('add')->check($data)) {
        //        $this->error($validate->getError());
        //    } 
          if(!empty($data['id'])) {
            return $this->update($data);
          }


         $res = model("Category")->add($data);
         if ($res) {
             $this->success('新增成功');
         } else {
             $this->error("新增失败");
         }
          


    }

   public function update($data) {
       $res = model("Category")->save($data, ['id' => intval($data['id'])]);
       if($res) {
           $this->success('更新成功');
       } else {
           $this->error('更新失败');
       }
   }


   public function listorder($id,$listorder) {
    //    echo $id."<br />";
    //    echo $listorder. "<br />";
    $res = model("Category")->save(['listorder'=>$listorder],['id'=>$id]);
    if($res) {
        $this->result($_SERVER['HTTP_REFEER'],1,'succeess');
    } else {
        $this->result($_SERVER['HTTP_REFEER'],0,'failure');
    }


   }


   public function status() {
           $data = input('get.'); 
           echo $data['status'];
           echo $data['id'];

          $res =  model("Category")->save(['status'=>$data['status']],['id'=>$data['id']]);

          if($res) {
              $this->success('状态更新成功');
          } else {
            $this->error('状态更新失败');

          }


   }






}
